package com.qf.smsplatform.service.Impl;
/*2021/11/3*/

import com.fasterxml.jackson.databind.Module;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.smsplatform.cache.TMenuCache;
import com.qf.smsplatform.constans.ResultCode;
import com.qf.smsplatform.events.UpdateTMenuEvent;
import com.qf.smsplatform.exception.AddDataException;
import com.qf.smsplatform.mapper.TMenuMapper;
import com.qf.smsplatform.pojo.CheckType;
import com.qf.smsplatform.pojo.TMenu;
import com.qf.smsplatform.service.TMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @YuTao
 */
@Service
@Transactional
public class TMenuServiceImpl implements TMenuService {

    private TMenuMapper tMenuMapper;

    private TMenuCache tMenuCache;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void settMenuCache(TMenuCache tMenuCache) {
        this.tMenuCache = tMenuCache;
    }
    @Autowired
    public void settMenuMapper(TMenuMapper tMenuMapper) {
        this.tMenuMapper = tMenuMapper;
    }
    //添加访问地址信息
    @Override
    public void insertTMenu(TMenu tMenu) {
        if(tMenu.isNull(CheckType.ADD)){
            throw new AddDataException("添加的地址信息不合法", ResultCode.DATA_ISNULL);
        }
        tMenuMapper.insertTMenu(tMenu);

        //添加信息后，发布一个事件，对缓存中的信息进行更新
        context.publishEvent(new UpdateTMenuEvent());
    }
    //对数据库中的可以访问的地址信息进行修改，特别是地址的state信息，控制地址是否可以访问
    @Override
    public void updateTMenu(TMenu tmenu) {
        if(tmenu.isNull(CheckType.UPDATE)){
            throw new AddDataException("修改的地址信息不合法", ResultCode.DATA_ISNULL);
        }
        tMenuMapper.updateTMenu(tmenu);


        //修改信息后，发布一个事件，对缓存中的信息进行更新
        context.publishEvent(new UpdateTMenuEvent());
    }
    //返回分页查询的访问地址信息
    @Override
    public PageInfo<TMenu> selectPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TMenu> allData = tMenuCache.getAllData();//从缓存中获取访问地址的相关数据
        //对集合中的数据进行分页过滤
        List<TMenu> collect = allData.stream().skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        PageInfo<TMenu> pageInfo=new PageInfo<>(collect);
        return pageInfo;
    }

    @Override
    public TMenu selectMenuByUrl(String url) {
        TMenu byKey = tMenuCache.getByKey(url);
        return byKey;
    }

}
